from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import PhoneNumber, Plan, Payment, UserProfile


class CustomUserCreationForm(UserCreationForm):
    """自定义用户注册表单"""
    email = forms.EmailField(required=True, label='邮箱')
    
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')
        labels = {
            'username': '用户名',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].help_text = '用户名将作为您的主手机号码'
        self.fields['password1'].help_text = '至少8个字符，不能全是数字'
        self.fields['password2'].help_text = '再次输入密码确认'

    def save(self, commit=True):
        user = super().save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user


class PhoneNumberForm(forms.ModelForm):
    """手机号码表单"""
    class Meta:
        model = PhoneNumber
        fields = ['number']
        labels = {
            'number': '手机号码',
        }
        widgets = {
            'number': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入11位手机号码',
                'maxlength': '11'
            })
        }

    def clean_number(self):
        number = self.cleaned_data.get('number')
        if number:
            # 检查号码是否已被其他用户注册（允许同一用户重复添加，由视图层处理）
            existing_phones = PhoneNumber.objects.filter(number=number)
            if existing_phones.exists():
                # 如果号码已存在，让视图层处理重复检查
                pass
        return number


class PlanSelectionForm(forms.Form):
    """套餐选择表单"""
    plan = forms.ModelChoiceField(
        queryset=Plan.objects.filter(is_active=True),
        empty_label="请选择套餐",
        label='选择套餐',
        widget=forms.Select(attrs={'class': 'form-control'})
    )


class PaymentForm(forms.ModelForm):
    """缴费表单"""
    class Meta:
        model = Payment
        fields = ['amount', 'payment_method', 'description']
        labels = {
            'amount': '缴费金额(元)',
            'payment_method': '缴费方式',
            'description': '备注',
        }
        widgets = {
            'amount': forms.NumberInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入缴费金额',
                'min': '0.01',
                'step': '0.01'
            }),
            'payment_method': forms.Select(attrs={'class': 'form-control'}),
            'description': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '可选，添加备注信息'
            })
        }

    def clean_amount(self):
        amount = self.cleaned_data.get('amount')
        if amount and amount <= 0:
            raise forms.ValidationError('缴费金额必须大于0')
        return amount


class UserProfileForm(forms.ModelForm):
    """用户资料表单"""
    class Meta:
        model = UserProfile
        fields = ['avatar']
        labels = {
            'avatar': '头像',
        }
        widgets = {
            'avatar': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*'
            })
        }


class PhoneNumberSwitchForm(forms.Form):
    """号码切换表单"""
    phone_number = forms.ModelChoiceField(
        queryset=PhoneNumber.objects.none(),
        empty_label="请选择要查询的号码",
        label='选择号码',
        widget=forms.Select(attrs={'class': 'form-control'})
    )

    def __init__(self, user=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if user:
            self.fields['phone_number'].queryset = PhoneNumber.objects.filter(user=user)
